<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('workorder.fields.quick Search Fields') })"
        ></TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { cloneDeep, isEmpty } from 'lodash-es'

defineOptions({
    name: 'workorder/fields',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['weigh-sort', 'edit', 'delete'])

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/workorder.Fields/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('workorder.fields.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            {
                label: t('workorder.fields.position'),
                prop: 'position',
                align: 'center',
                render: 'tag',
                operator: 'eq',
                sortable: false,
                replaceValue: {
                    wo: '案件提交',
                    user: t('workorder.fields.position user'),
                    engineer: '工程师反馈',
                    initial: '初步分析',
                    detailed: '深入分析',
                },
                width: 160,
            },
            {
                label: t('workorder.fields.title'),
                prop: 'title',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false,
                showOverflowTooltip: false,
            },
            {
                label: t('workorder.fields.name'),
                prop: 'name',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false,
                showOverflowTooltip: false,
            },
            {
                label: t('workorder.fields.type'),
                prop: 'type',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false,
            },
            {
                label: t('workorder.fields.default'),
                prop: 'default',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false,
            },
            {
                show: false,
                label: t('workorder.fields.backend_show'),
                prop: 'backend_show',
                align: 'center',
                render: 'switch',
                operator: 'eq',
                sortable: false,
                replaceValue: { '0': t('workorder.fields.backend_show 0'), '1': t('workorder.fields.backend_show 1') },
            },
            {
                show: false,
                label: t('workorder.fields.backend_com_search'),
                prop: 'backend_com_search',
                align: 'center',
                render: 'switch',
                operator: 'eq',
                sortable: false,
                replaceValue: { '0': t('workorder.fields.backend_com_search 0'), '1': t('workorder.fields.backend_com_search 1') },
            },
            {
                show: false,
                label: t('workorder.fields.backend_sort'),
                prop: 'backend_sort',
                align: 'center',
                render: 'switch',
                operator: 'eq',
                sortable: false,
                replaceValue: { '0': t('workorder.fields.backend_sort 0'), '1': t('workorder.fields.backend_sort 1') },
            },
            { label: t('workorder.fields.weigh'), prop: 'weigh', align: 'center', operator: 'RANGE', sortable: 'custom' },
            {
                label: t('workorder.fields.status'),
                prop: 'status',
                align: 'center',
                render: 'switch',
                operator: 'eq',
                sortable: false,
                replaceValue: { '0': t('workorder.fields.status 0'), '1': t('workorder.fields.status 1') },
            },
            {
                label: t('workorder.fields.update_time'),
                prop: 'update_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            {
                label: t('workorder.fields.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: 'RANGE',
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss',
            },
            { label: t('Operate'), align: 'center', width: 140, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined, 'autofill', 'basic_info', 'backend_show', 'backend_com_search', 'backend_sort', 'status'],
        defaultOrder: { prop: 'weigh', order: 'desc' },
    },
    {
        defaultItems: {
            position: 'wo',
            autofill: '0',
            basic_info: '1',
            message: '0',
            backend_show: '1',
            backend_com_search: '1',
            backend_sort: '1',
            weigh: 0,
            status: '1',
        },
    },
    {
        toggleForm: ({ operate }) => {
            if (operate == 'Add') {
                baTable.form.extend!.field = {
                    dict: `key1=value1
key2=value2`,
                }
            }
        },
        onSubmit: ({ formEl, operate, items }) => {
            var items = cloneDeep(items)
            for (const key in items) {
                if (items[key] === null) {
                    delete items[key]
                }
            }

            operate = operate.replace(operate[0], operate[0].toLowerCase())

            // 表单验证通过后执行的api请求操作
            const submitCallback = () => {
                baTable.form.submitLoading = true
                items.tip_msg = baTable.form.extend!.field.tip
                items.input_extend = baTable.form.extend!.field.inputExtend
                items.formitem_extend = baTable.form.extend!.field.extend

                delete baTable.form.extend!.field.tip
                delete baTable.form.extend!.field.extend
                delete baTable.form.extend!.field.inputExtend

                baTable.api
                    .postData(operate, { ...items, ...baTable.form.extend!.field })
                    .then((res) => {
                        baTable.onTableHeaderAction('refresh', {})
                        baTable.form.operateIds?.shift()
                        if (baTable.form.operateIds!.length > 0) {
                            baTable.toggleForm('edit', baTable.form.operateIds)
                        } else {
                            baTable.toggleForm()
                        }
                        baTable.runAfter('onSubmit', { res })
                    })
                    .finally(() => {
                        baTable.form.submitLoading = false
                    })
            }

            if (formEl) {
                baTable.form.ref = formEl
                formEl.validate((valid) => {
                    if (valid) {
                        submitCallback()
                    }
                })
            } else {
                submitCallback()
            }
            return false
        },
    },
    {
        requestEdit: ({ res }) => {
            baTable.form.extend!.dataEbak = {
                type: res.data.row.type,
                data_type: res.data.row.data_type,
                dict: res.data.row.dict,
            }
            if (isEmpty(baTable.form.extend!.field)) {
                baTable.form.extend!.field = {}
            }
            baTable.form.extend!.field.name = res.data.row.name
            baTable.form.extend!.field.title = res.data.row.title
            baTable.form.extend!.field.type = res.data.row.type
            baTable.form.extend!.field.tip = res.data.row.tip_msg
            baTable.form.extend!.field.rule = res.data.row.rule
            baTable.form.extend!.field.extend = res.data.row.formitem_extend
            baTable.form.extend!.field.inputExtend = res.data.row.input_extend
            baTable.form.extend!.field.dict = res.data.row.dict
        },
    }
)

baTable.form.extend!.field = {
    dict: `key1=value1
key2=value2`,
}

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss"></style>
